package com.yongchun.controller;

import com.alibaba.fastjson.JSONObject;

import com.yongchun.commons.StringUtil;
import com.yongchun.config.TokenVO;
import com.yongchun.pubInter.BusinessException;
import com.yongchun.pubInter.BusinessExceptionEnum;
import com.yongchun.pubInter.SkException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author afeng
 * @version 1.0
 * @date 2023/3/1 下午5:53
 */
public class ApiRestController extends BaseController{
    public static String MY_SECRET = "mySecret";
    public static String USER_HEADER_KEY = "wechatauthorization";
    public static String USER_HEADER_KEY_PREFIX = "wechat ";
    /**
     * 设置用户token
     *
     * @param tokenVO
     * @param response
     */
    protected void setToken(TokenVO tokenVO, HttpServletResponse response) {
        String token = Jwts.builder()
                .setSubject(JSONObject.toJSONString(tokenVO))
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000))
                .signWith(SignatureAlgorithm.HS512, MY_SECRET)
                .compact();
        response.addHeader(USER_HEADER_KEY, USER_HEADER_KEY_PREFIX + token);
    }


    /**
     * 获取用户信息
     *
     * @param request
     * @return
     * @throws BusinessException
     */
    protected TokenVO getToken(HttpServletRequest request) throws SkException {
        String token = request.getHeader(USER_HEADER_KEY);
        if (StringUtil.isNullOrEmpty(token)) {
            throw new BusinessException(BusinessExceptionEnum.TOKEN_NULL);
        }
        try {


            String mapStr = Jwts.parser()
                    .setSigningKey(MY_SECRET)
                    .parseClaimsJws(token.replace(USER_HEADER_KEY_PREFIX, ""))
                    .getBody()
                    .getSubject();

            return JSONObject.parseObject(mapStr, TokenVO.class);


        } catch (Exception e) {

        }
        return null;
    }
}
